package com.clementheliou.cheliou.web.core.security.authentication.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.clementheliou.cheliou.business.technical.security.authentication.model.AuthenticationDetails;
import com.clementheliou.cheliou.web.util.cookie.CookieUtils;

/**
 * Sucess handler that is pratically equals to the
 * {@link SavedRequestAwareAuthenticationSuccessHandler} one. We just create a
 * locale cookie for the principal before the redirection.
 * 
 * @author Clément HELIOU (clement.heliou@gmail.com)
 * @see {@link ApplicationContext};
 * @see {@link ApplicationContextAware};
 * @see {@link SavedRequestAwareAuthenticationSuccessHandler}.
 * @since 1.0
 */
public class LocaleCookieCreationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler implements ApplicationContextAware {

	/**
	 * Utilities about cookies.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @see {@link CookieUtils}.
	 * @since 1.0
	 */
	private CookieUtils cookieUtils;

	/**
	 * <i> {@inheritDoc} </i>
	 * <p>
	 * After the authentication success, we create the locale cookie.
	 * </p>
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
		cookieUtils.createLocaleCookie((AuthenticationDetails) authentication.getPrincipal(), response);
		super.onAuthenticationSuccess(request, response, authentication);
	}

	/**
	 * <i>{@inheritDoc}</i>
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.cookieUtils = applicationContext.getBean(CookieUtils.class);
	}

}
